package com.neuedu.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.neuedu.dao.CartDAO;
import com.neuedu.dao.impl.CartDAOImpl;
import com.neuedu.entity.Cart;
import com.neuedu.entity.User;

@WebServlet("*.cart")
public class CartServlet  extends HttpServlet{
	  
  CartDAO cartdao=new CartDAOImpl();
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String uri=req.getRequestURI();
		System.out.println(uri);
		String path=uri.substring(uri.lastIndexOf("/")+1, uri.lastIndexOf("."));
		if("add".equals(path)) {
			add(req, resp);
		}

		
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String gid=req.getParameter("gid");
		
		String gnumber=req.getParameter("gnumber");
		
	   HttpSession session=req.getSession();
	   Integer uid=null;
	   boolean flag=true;
	   if(session.getAttribute("user")==null) {
		   flag=false;
	   }else {
	      uid=((User)session.getAttribute("user")).getUid();
	   
	   }
	   
	   if(flag) {
		   
		   Cart cart=new Cart();
		   cart.setGid(Integer.valueOf(gid));
		   cart.setUid(uid);
		   cart.setGnumber(Integer.valueOf(gnumber));
		   
		   int i=cartdao.updatecart(cart);
		   if(i==-1) {
			   flag=false;
		   }
	   }
	   
	   String jsonStr="{\"flag\":"+flag+"}";
		System.out.println(jsonStr);
		resp.getWriter().println(jsonStr);
	   	}

}
